package cn.lichenes.controller;

import cn.lichenes.config.AlipayConfig;
import cn.lichenes.entity.Address;
import cn.lichenes.entity.Indent;
import cn.lichenes.entity.User;
import cn.lichenes.log.SystemLog;
import cn.lichenes.service.AddressService;
import cn.lichenes.service.IndentService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AliPayController {

    @Autowired
    private IndentService indentService;
    @Autowired
    private AddressService addressService;

    @GetMapping("/payment/{id}")
    public synchronized String payment(@PathVariable(value = "id")Integer id, HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        if (user != null){
            Indent indent = indentService.findById(id);
            List<Address> addresses = addressService.findAll(user);
            Map<String,Object> map = new HashMap<>();
            map.put("indent",indent);
            map.put("addresses",addresses);
            model.addAllAttributes(map);
            return "payment";
        }
        return "redirect:/login";
    }

    @PostMapping("/order")
    @ResponseBody
    public boolean orderAddAddress(Integer aid,Integer oid){
        System.out.println(aid+","+oid);
        boolean flag = indentService.addAddress(oid, aid);
        return flag;
    }

    @PostMapping(value = "/alipay", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String  alipay(String oId, String p_name, String money, String WIDbody){
        System.out.println(oId+","+p_name+","+money+","+WIDbody);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = oId;
//		String out_trade_no =1399+"";
        //付款金额，必填
        String total_amount = money;
//		String total_amount ="3999";
        //订单名称，必填
        String subject = p_name;
//		String subject = "小米";
        //商品描述，可空
        String body = WIDbody;
//		String body ="付款";
        System.out.println("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;
    }

    //异步
    @SystemLog(value = "用户购买商品",status = "user")
    @PostMapping("/notify")
    @ResponseBody
    public boolean alipayNotify(HttpServletRequest request,HttpServletResponse response){
        // 商户订单号
        String out_trade_no = request.getParameter("out_trade_no");
        // 支付宝交易号
        String trade_no = request.getParameter("trade_no");
        // 付款金额
        String total_amount = request.getParameter("total_amount");
        //订单号
        Integer oId =Integer.parseInt(out_trade_no.substring(14));
        response.setContentType("text/html;charset=utf-8");
        System.out.println("订单号:" + out_trade_no);
        System.out.println("支付宝交易号" + trade_no);
        System.out.println("付款金额" + total_amount);
        System.out.println("订单号"+oId);
        boolean flag = indentService.alipayIndent(oId);
        System.out.println(flag);
        return flag;
    }

    //同步
    @GetMapping("/success")
    public String success(HttpServletRequest request,HttpServletResponse response){
        return "success";
    }
}
